﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using FDStudio.Core.Common.Constants;
using FDStudio.Core.Entities;
using FDStudio.Core.Entities.Factories;
using FDStudio.Core.Entities.Query;
using FDStudio.Core.Repositories;
using FDStudio.Core.Runtime;

namespace FDStudio.Core.Services
{
    /*
     CreatedOn: 2018-03-08
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 只写服务基类
    /// </summary>
    public class WriteOnlyServiceBase<T> : IWriteOnlyService<T> where T : class, IEntity
    {
        private IWriteOnlyRepository<T> _repository;

        protected IApiResultFactory ApiResultFactory;

        public WriteOnlyServiceBase(IWriteOnlyRepository<T> repository)
        {
            _repository = repository;
            ApiResultFactory = RuntimeContext.Current.Container.Resove<IApiResultFactory>();
        }

        /// <summary>
        /// 获取当仓储
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <returns></returns>
        protected U Repository<U>()
        {
            return (U)_repository;
        }

        public virtual bool Add(T model)
        {
            return _repository.Add(model);
        }

        public virtual bool Delete(T model)
        {
            return _repository.Delete(model);
        }

        public bool Delete(long id)
        {
            return _repository.Delete(id);
        }

        public virtual bool Delete(Expression<Func<T, bool>> condition)
        {
            return _repository.Delete(condition);
        }

        public virtual bool Update(T model)
        {
            return _repository.Update(model);
        }

        /// <summary>
        /// 捕获性执行
        /// </summary>
        /// <param name="action">执行的业务</param>
        /// <param name="exceptionAction">异常动作</param>
        /// <param name="finishAction">结束操作</param>
        /// <returns></returns>
        public IApiResult<R> Execute<R>(Func<IApiResult<R>> action, Action<Exception> exceptionAction = null, Action finishAction = null)
        {
            try
            {
                return action?.Invoke();
            }
            catch (Exception ex)
            {
                exceptionAction?.Invoke(ex);
                return ApiResultFactory.Error<R>(ResultCode.InnerException, ex);
            }
            finally
            {
                finishAction?.Invoke();
            }
        }

        public IApiResult<List<long>> AddBatch(IEnumerable<T> senderSessions)
        {
            return Execute(() =>
            {
                Repository<IWriteOnlyRepository<T>>().BeginTransaction();
                var ids = new List<long>();
                foreach (var sender in senderSessions)
                {
                    if (Add(sender))
                    {
                        ids.Add(sender.Id);
                    }
                    else
                    {
                        throw new Exception("添加失败");
                    }
                }
                Repository<IWriteOnlyRepository<T>>().CommitTransaction();

                return ApiResultFactory.Success(ResultCode.Success, "Ok", ids);
            }, ex =>
            {
                Repository<IWriteOnlyRepository<T>>().RollbackTransaction();
            });
        }

        public void BeginTransaction()
        {
            _repository.BeginTransaction();
        }

        public void CommitTransaction()
        {
            _repository.CommitTransaction();
        }

        public void RollbackTransaction()
        {
            _repository.RollbackTransaction();
        }
    }
}
